package com.example.myapplication;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.widget.ViewPager2;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.R;
import com.example.myapplication.Video;
import com.example.myapplication.VideoApiResponse;
import com.example.myapplication.ApiService;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class VideoFragment extends Fragment {

    private static final String TAG = "VideoFragment";
    private static final String BASE_URL = "https://tucdn.wpon.cn/";
    private ViewPager2 viewPagerVideos;
    private VideoAdapter videoAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<Video> videoList = new ArrayList<>();
    private VideoViewHolder currentPlayingViewHolder;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: VideoFragment created");
        View root = inflater.inflate(R.layout.fragment_video, container, false);

        viewPagerVideos = root.findViewById(R.id.viewPagerVideos);
        swipeRefreshLayout = root.findViewById(R.id.swipeRefreshLayout);

        videoAdapter = new VideoAdapter(videoList, viewPagerVideos);
        viewPagerVideos.setAdapter(videoAdapter);

        swipeRefreshLayout.setOnRefreshListener(this::fetchVideos);

        viewPagerVideos.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.d(TAG, "onPageSelected: position = " + position);
                if (currentPlayingViewHolder != null && currentPlayingViewHolder.player != null) {
                    currentPlayingViewHolder.player.pause();
                    Log.d(TAG, "onPageSelected: Paused previous video at position: " + (position > 0 ? position - 1 : "N/A"));
                }

                RecyclerView recyclerView = (RecyclerView) viewPagerVideos.getChildAt(0);
                VideoViewHolder newHolder = (VideoViewHolder) recyclerView.findViewHolderForAdapterPosition(position);

                if (newHolder != null && newHolder.player != null) {
                    newHolder.player.play();
                    currentPlayingViewHolder = newHolder;
                    Log.d(TAG, "onPageSelected: Playing video at position: " + position);
                } else {
                    Log.w(TAG, "onPageSelected: newHolder or newHolder.player is null for position: " + position);
                }
            }
        });

        fetchVideos();

        return root;
    }

    private void fetchVideos() {
        Log.d(TAG, "fetchVideos: Fetching videos from API");
        swipeRefreshLayout.setRefreshing(true);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiService apiService = retrofit.create(ApiService.class);
        Call<VideoApiResponse> call = apiService.getVideos("json");

        call.enqueue(new Callback<VideoApiResponse>() {
            @Override
            public void onResponse(@NonNull Call<VideoApiResponse> call, @NonNull Response<VideoApiResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    VideoApiResponse apiResponse = response.body();
                    Log.d(TAG, "onResponse: API Response Error Code: " + apiResponse.getError() + ", Result: " + apiResponse.getgetResult() + ", Video URL: " + apiResponse.getVideoUrl());

                    if (apiResponse.getError() == 0 && apiResponse.getVideoUrl() != null) {
                        // 清除旧数据并添加新数据
                        videoList.clear();
                        Video video = new Video();
                        String videoUrl = apiResponse.getVideoUrl();
                        if (videoUrl != null && videoUrl.startsWith("//")) {
                            videoUrl = "https:" + videoUrl;
                        }
                        video.setUrl(videoUrl);
                        // 这里可以根据需要设置title和cover，如果API响应中没有，可以设置为null或默认值
                        video.setTitle("随机视频"); // 假设一个默认标题
                        video.setCover(null); // 假设没有封面
                        videoList.add(video);

                        videoAdapter.notifyDataSetChanged();
                        viewPagerVideos.post(() -> {
                            if (videoList.size() > 0) {
                                // 确保视频在加载后立即播放
                                if (currentPlayingViewHolder != null && currentPlayingViewHolder.player != null) {
                                    currentPlayingViewHolder.player.pause();
                                }
                                RecyclerView recyclerView = (RecyclerView) viewPagerVideos.getChildAt(0);
                                VideoViewHolder newHolder = (VideoViewHolder) recyclerView.findViewHolderForAdapterPosition(0);
                                if (newHolder != null && newHolder.player != null) {
                                    newHolder.player.play();
                                    currentPlayingViewHolder = newHolder;
                                }
                            }
                        });

                    } else {
                        Toast.makeText(getContext(), "API返回错误: " + "Error Code: " + apiResponse.getError() + ", Result: " + apiResponse.getgetResult(), Toast.LENGTH_LONG).show();
                        Log.e(TAG, "onResponse: API returned error: " + "Error Code: " + apiResponse.getError() + ", Result: " + apiResponse.getgetResult());
                    }
                } else {
                    Log.e(TAG, "onResponse: Failed to fetch videos, code: " + response.code() + ", message: " + response.message());
                    Toast.makeText(getContext(), "Failed to fetch videos", Toast.LENGTH_SHORT).show();
                }
                swipeRefreshLayout.setRefreshing(false);
                Log.d(TAG, "onResponse: swipeRefreshLayout setRefreshing(false)");
            }

            @Override
            public void onFailure(@NonNull Call<VideoApiResponse> call, @NonNull Throwable t) {
                Log.e(TAG, "onFailure: Error fetching videos: " + t.getMessage(), t);
                Toast.makeText(getContext(), "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                swipeRefreshLayout.setRefreshing(false);
                Log.d(TAG, "onFailure: swipeRefreshLayout setRefreshing(false)");
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: Fragment paused");
        if (currentPlayingViewHolder != null && currentPlayingViewHolder.player != null) {
            currentPlayingViewHolder.player.pause();
            Log.d(TAG, "onPause: Paused current playing video");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: Fragment resumed");
        if (currentPlayingViewHolder != null && currentPlayingViewHolder.player != null) {
            currentPlayingViewHolder.player.play();
            Log.d(TAG, "onResume: Resumed current playing video");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView: Fragment view destroyed");
        if (currentPlayingViewHolder != null) {
            currentPlayingViewHolder.releasePlayer();
            currentPlayingViewHolder = null;
            Log.d(TAG, "onDestroyView: Released current playing video player");
        }
    }
}